<?php
namespace core\modules;
use core\Res;

/**
 * 文件上传组件
 */

class Uploader {


  static public $default_size=100*1024*1024;
  static public $default_ext="jpg,png,gif,bpm,doc,docx,xls,xlsx,ppt,pptx,txt,pdf,mp3,mp4,zip,rar,7z";

  public $size="";
  public $ext="";


  function __construct($size="",$ext=""){

    // 大小限制
    if (!empty($size)) $this->setSize($size);
    // 文件类型
    if (!empty($ext)) $this->setExt($ext);
  }
  public function getFile($var=""){
    if (empty($var)){
      $var=["upload","file","files","image","images"];
    }
    if (!is_array($var)) $var=explode(",",$var);
    $file=false;
    foreach ($var as $v) {
      $file = request()->file(trim($v));
      if ($file){
        break;
      }
    }
    return $file;
  }

  // 上传图片
  public function image($var=""){
    if (empty($this->ext)) $this->setExt("jpg,gif,png,bpm");
    $this->doUpload("images",$var);
  }
  // 上传文档
  public function doc($var=""){
    if (empty($this->ext)) $this->setExt("doc,docx,xls,xlsx,ppt,pptx,txt,pdf");
    $this->doUpload("doc",$var);
  }
  // 上传归档文件
  public function zip($var=""){
    if (empty($this->ext)) $this->setExt("zip,rar,7z");
    $this->doUpload("zip",$var);
  }
  // 上传媒体文件
  public function media($var=""){
    if (empty($this->ext)) $this->setExt("mp3,mp4");
    $this->doUpload("media",$var);
  }

  // 设置大小
  public function setSize($size){
    $this->size=$size;
  }
  // 设置类型
  public function setExt($ext){
    $this->ext=$ext;
  }
  // 上传操作
  public function doUpload($dir,$var=""){
    $dir=trim($dir,'/');
    // 获取表单上传文件 例如上传了
    $file = $this->getFile($var);


    // 移动到框架应用根目录/uploads/ 目录下
    $info = $file->validate([
      'size'=>empty($this->size)?static::$default_size:$this->size,
      'ext'=>empty($this->ext)?static::$default_ext:$this->ext
    ])->move( './'.Res::$store.'/'.$dir);


    if($info){
        // 成功上传后 获取上传信息
        $ext=$info->getExtension();
        $size=$info->getExtension();
        // 文件路径
        $path=$dir."/".$info->getSaveName();
        $url=Res::url($path);

        $result=[
          'name'=>$info->getInfo("name"),
          'newname'=>$info->getFilename(),
          'path'=>$path,
          'url'=>$url,
          'size'=>$size,
          'ext'=>$ext,
        ];
        $this->ok($result);

    }else{
        // 上传失败获取错误信息
        $this->error('上传失败: '.$file->getError());
    }


  }
  // 兼容ckeditor的输出
  public function ok($data){
    $send=array(
			'result'=>true,
      'code'=>0,
			'data'=>$data,
      'uploaded'=>true,
      'url'=>isset($data['url'])?$data['url']:"",
		);
		json($send)->send();
    die();
  }
  public function error($data){
    $send=array(
			'result'=>false,
      'code'=>0,
			'data'=>$data,
      'uploaded'=>false,
      'url'=>isset($data['url'])?$data['url']:"",
		);
		json($send)->send();
    die();
  }


}
